<template>
  <div class="UserIndexDialog">
    <el-dialog
      :close-on-click-modal="false"
      :title="dialog.id ? '编辑人员' : '新增人员'"
      :visible="dialog.visible"
      width="630px"
      :before-close="closeFn"
    >
      <span>
        <el-form ref="newUserForm" :model="newUserForm" :rules="newUserFormRules" label-width="140px">
          <el-form-item label="人员名称：" prop="userName">
            <el-input v-model.trim="newUserForm.userName"
            placeholder="请输入"
            maxlength="5"
            show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="角色：" prop="roleId">
            <el-select v-model="newUserForm.roleId" placeholder="请选择">
              <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系电话：" prop="mobile">
            <el-input v-model.trim="newUserForm.mobile"
            placeholder="请输入"
            maxlength="11"
            show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="负责区域：" prop="regionId">
            <el-select v-model="newUserForm.regionId" placeholder="请选择">
              <el-option
              v-for="item in regionList?.currentPageRecords"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="头像：" prop="image">
            <el-upload
              action="baseUrl"
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              >
              <img v-if="newUserForm.image" :src="newUserForm.image" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <template #tip><br>支持扩展名：jpg、png，文件不得大于100kb</template>
            </el-upload>
          </el-form-item>
          <el-form-item label="状态：">
            <el-checkbox v-model="newUserForm.status">是否启用</el-checkbox>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeFn" size="medium">取消</el-button>
        <!-- 新建人员确定 -->
        <el-button v-if="!dialog.id" type="primary" size="medium" @click="postUser">确定</el-button>
        <!-- 修改人员确定 -->
        <el-button v-if="dialog.id" type="primary" size="medium" @click="putUser">确定</el-button>
      </span>
    </el-dialog>
    <!-- 弹出框结束 -->
  </div>
</template>

<script>
import request from '@/utils/request'
import { updataImg } from '@/api/Equipment'
import {
  getRole,
  getRegion,
  addUser,
  putUser
} from '@/api/UserAPIs'
export default {
  props: {
    dialog: {
      type: Object,
      required: true
    },
    userList: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      // 表单信息
      newUserForm: {
        userName: '',
        roleId: '',
        mobile: '',
        regionId: '',
        regionName: '',
        image: '',
        status: false
      },
      // 表單校驗
      newUserFormRules: {
        userName: [{ required: true, message: '用户名不能为空' }],
        roleId: [{ required: true, message: '角色不能为空' }],
        mobile: [{ required: true, message: '联系电话不能为空' }],
        regionId: [{ required: true, message: '负责区域不能为空' }],
        image: [{ required: true, message: '头像未上传' }]
      },
      // 头像上传
      baseUrl: request.defaults.baseURL,
      // 角色列表
      roleList: [],
      // 区域列表
      regionList: []
    }
  },
  async created () {
    const { data: roleList } = await getRole()
    this.roleList = roleList
    const { data: regionList } = await getRegion({
      pageIndex: 1,
      pageSize: 114514
    })
    this.regionList = regionList
  },
  methods: {
    async closeFn () {
      // 重置状态
      this.$emit('update:dialog', {
        visible: false, // 是否显示
        id: 0
      })
      // 重置表单状态
      this.newUserForm = {
        userName: '',
        roleId: '',
        mobile: '',
        regionId: '',
        regionName: '',
        image: '',
        status: false
      }
      await this.$refs.newUserForm.resetFields()
    },
    // 图片上传
    async beforeAvatarUpload (file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt = file.size / 1024 / 1024 < 0.1
      let fileType = false
      if (isJPG) {
        fileType = true
      } else if (isPNG) {
        fileType = true
      } else {
        this.$message.error('上传头像图片只能是 JPG / PNG 格式!')
      }
      if (!isLt) {
        this.$message.error('上传头像图片大小不能超过 100kb!')
      }
      if (fileType && isLt) {
        const formData = new FormData()
        formData.append('fileName', file)
        const { data } = await updataImg(formData)
        this.newUserForm.image = data
        console.log(this.newUserForm.image)
      }
      return fileType && isLt
    },
    // 新增人员
    async postUser () {
      try {
        await this.$refs.newUserForm.validate()
        await addUser(this.newUserForm)
      } catch (e) {
        console.log(e)
      } finally {
        this.closeFn()
      }
    },
    async putUser () {
      try {
        await this.$refs.newUserForm.validate()
        await putUser({
          id: this.dialog.id,
          data: this.newUserForm
        })
      } catch (e) {
        console.log(e)
      } finally {
        this.closeFn()
      }
    }
  },
  watch: {
    dialog: {
      handler (newVal) {
        console.log(newVal)
        if (newVal.id) {
          const res = this.userList.find(item => item.id === newVal.id)
          this.newUserForm = {
            userName: res.userName,
            roleId: res.roleId,
            mobile: res.mobile,
            regionId: res.regionId,
            regionName: res.regionName,
            image: res.image,
            status: res.status
          }
          console.log(this.newUserForm)
        }
      },
      deep: true // 深入監聽
    },
    newUserForm: {
      handler (newVal) {
        // 匹配ID来设置 regionName
        if (newVal.regionId) {
          this.newUserForm.regionName = this.regionList.currentPageRecords.find(item => item.id === newVal.regionId).name
        }
      },
      deep: true // 深入監聽
    }
  }
}
</script>

<style lang="scss" scoped>
.UserIndexDialog {
  .el-form{
    padding-right: 40px;
    .el-select {
      width: 100%;
    }
  }
  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    background: #f3f6fb;
    padding: 5px;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }
  .avatar {
    width: 78px;
    height: 78px;
    display: block;
  }
}
</style>
